<template>
    <div class="container" style="display: flex">
        <!--查询部分-->
        <div class="left">
            <el-input
                    style="margin-bottom: 20px"
                    size="small"
                    placeholder="请输入内容"
                    prefix-icon="el-icon-search"
                    v-model="filterText">
            </el-input>

            <el-tree
                    @node-click="deptChange"
                    class="filter-tree"
                    :data="deptTree"
                    :props="{label:'name',children: 'childDept'}"
                    default-expand-all
                    :filter-node-method="filterNode"
                    ref="tree">
            </el-tree>
        </div>

        <!--右边部分 begin-->
        <div class="right">
            <!--查询部分-->
            <el-form ref="userQueryForm" :inline="true" :model="userQueryForm" style="margin-bottom: 20px">
                <el-form-item prop="name" size="small" label="用户姓名">
                    <el-input clearable @keyup.enter.native="searchUser" v-model="userQueryForm.name"
                              placeholder="请输入用户名"></el-input>
                </el-form-item>

                <el-form-item prop="mobile" size="small" label="用户手机">
                    <el-input clearable @keyup.enter.native="searchUser" v-model="userQueryForm.mobile"
                              placeholder="请输入手机号"></el-input>
                </el-form-item>

                <el-form-item prop="status" size="small" label="用户状态">
                    <el-select clearable v-model="userQueryForm.status" placeholder="选择用户状态">
                        <el-option label="正常" value=1></el-option>
                        <el-option label="禁用" value=0></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item prop="dateTimePickerValue" size="small" label="创建时间">
                    <el-date-picker
                            value-format="yyyy-MM-dd HH:mm:ss"
                            @change="formatTime"
                            type="datetimerange"
                            v-model="userQueryForm.dateTimePickerValue"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"/>
                </el-form-item>

                <el-form-item size="mini">
                    <el-button :disabled="authenticate('查询')" @click="searchUser" style="width: 80px" type="primary"><i
                            class="iconfont icon-search-line"/><span>查询</span>
                    </el-button>
                </el-form-item>

                <el-form-item size="mini">
                    <el-button @click="$refs.userQueryForm.resetFields();userQueryForm.deptIds=[]" style="width: 80px"
                               type="normal"><i
                            class="iconfont icon-zhongzhi-"/><span>重置</span>
                    </el-button>
                </el-form-item>

                <el-form-item size="mini">
                    <el-button :disabled="authenticate('新增')" plain style="width: 80px" type="primary" @click="addUser">
                        <i class="iconfont icon-jia"/>
                        <span>新增</span>
                    </el-button>
                </el-form-item>
            </el-form>
            <!--查询部分-->

            <!--菜单列表 列表部分-->
            <el-table
                    :header-cell-style="{'text-align':'center',background:'#f8f8f9',color:'#606266'}"
                    :cell-style="{'text-align':'center'}"
                    :data="userDatas"
                    style="width: 100%;margin-bottom: 40px;"
                    row-key="id"
                    default-expand-all>
                <el-table-column
                        prop="name"
                        label="用户名">
                </el-table-column>

                <el-table-column
                        prop="nickname"
                        label="用户昵称">
                </el-table-column>

                <el-table-column
                        prop="deptName"
                        label="部门">
                </el-table-column>

                <el-table-column
                        prop="mobile"
                        label="手机号">
                </el-table-column>

                <el-table-column
                        width="200"
                        label="状态">
                    <template slot-scope="scope">
                        <el-switch
                                :disabled="authenticate('状态')"
                                v-model="scope.row.status"
                                @change="statusChange(scope.row)"
                                :active-value="'1'"
                                :inactive-value="'0'"
                                active-color="#13ce66"
                                inactive-color="#a9acb8"
                                active-text="启用"
                                inactive-text="禁用">
                        </el-switch>
                    </template>
                </el-table-column>

                <el-table-column
                        prop="createTime"
                        sortable
                        label="创建时间">
                </el-table-column>


                <el-table-column
                        width="300"
                        fixed="right"
                        label="操作">
                    <template slot-scope="scope">
                        <el-button :disabled="authenticate('编辑')" size="mini" type="primary"
                                   @click="editUser(scope.row)" round>编辑
                        </el-button>
                        <el-button :disabled="authenticate('修改密码')" size="mini" type="warning"
                                   @click="passwdVisible=true;userForm=scope.row;" round>
                            修改密码
                        </el-button>
                        <el-button :disabled="authenticate('删除')" size="mini" type="danger"
                                   @click="delUser(scope.row,scope.$index)" round>删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
            <!-- 分页组件 -->
        </div>
        <!--右边部分 end-->

        <!--添加菜单 dialog-->
        <el-dialog @close="closeDialog" :title="dialogName"
                   :visible.sync="addUserVisible">
            <!--label-width 表单里面label的标签宽度-->
            <el-form class="myform" ref="userAddForm" label-position="right" :inline="true" :rules="userRules"
                     :model="userForm">

                <el-form-item prop="name" label="用户姓名">
                    <el-input v-model="userForm.name"></el-input>
                </el-form-item>

                <el-form-item v-if="dialogName==='添加用户'" prop="password" label="用户密码">
                    <el-tooltip placement="right" popper-class="mypopper">
                        <div slot="content">密码规则提示：<br/>密码首字母必须大写
                            <br/>大小写字母、数字、特殊字符四选三
                            <br/>长度：8-16位
                        </div>
                        <el-input :type="showPWFlag?'text':'password'" v-model="userForm.password">
                            <i slot="suffix" :class="showPWFlag?'iconfont icon-yanjing':'iconfont icon-yanjing_bi'"
                               @click="showPWFlag=!showPWFlag"/>
                        </el-input>
                    </el-tooltip>
                </el-form-item>

                <el-form-item prop="deptId" label="归属部门">
                    <!--这里是引用的第三方组件-->
                    <el-select-tree
                            :check-strictly="true"
                            :clearable="true"
                            style="width: 202px"
                            :accordion="true"
                            placeholder="归属部门"
                            :props="{ value: 'id', label: 'name', children: 'childDept'}"
                            :data="dialogDeptTree"
                            v-model="userForm.deptId">
                    </el-select-tree>
                </el-form-item>

                <el-form-item prop="jobId" label="用户岗位">
                    <el-select clearable filterable style="width: 202px" v-model="userForm.jobId" placeholder="请指定用户岗位">
                        <el-option v-for="option in jobDatas"
                                   :label="option.name"
                                   :value="option.id"
                                   :key="option.id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item prop="sex" label="用户性别">
                    <el-radio :key="index" v-for="(item,index) in $dictMap('sex')" v-model="userForm.sex"
                              :label="item.value">{{item.desc}}
                    </el-radio>
                </el-form-item>

                <el-form-item prop="roleIds" label="用户角色">
                    <el-select multiple clearable filterable style="width: 202px" v-model="userForm.roleIds"
                               placeholder="请指定用户角色(多选)">
                        <el-option v-for="option in roleDatas"
                                   :label="option.name"
                                   :value="option.id"
                                   :key="option.id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item prop="mobile" label="手机号码">
                    <el-input v-model="userForm.mobile"></el-input>
                </el-form-item>

                <el-form-item prop="nickname" label="用户昵称">
                    <el-input v-model="userForm.nickname"></el-input>
                </el-form-item>

                <el-form-item prop="email" label="邮箱">
                    <el-input v-model="userForm.email"></el-input>
                </el-form-item>


                <el-form-item v-if="!userForm.id" prop="status" label="用户状态">
                    <el-radio :key="index" v-for="(item,index) in $dictMap('status')" v-model="userForm.status"
                              :label="item.value">
                        {{item.desc}}
                    </el-radio>
                    <!--<el-radio v-model="userForm.status" :label="0">禁用</el-radio>-->
                </el-form-item>

                <el-form-item prop="remarks" label="备注" style="display: block">
                    <el-input
                            style="width:493px"
                            type="textarea"
                            :rows="4"
                            placeholder="备注内容"
                            v-model="userForm.remarks">
                    </el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="oprUser">确 定</el-button>
            </div>
        </el-dialog>
        <!--添加菜单 dialog-->


        <!--修改密码dialog begin -->
        <el-dialog @close="closeDialog"
                   title="修改密码"
                   :visible.sync="passwdVisible">
            <!--label-width 表单里面label的标签宽度-->
            <el-form ref="passwdForm" label-position="right" :rules="passwdRules" :model="passwdForm"
                     label-width="80px">

                <el-form-item prop="newPasswd" label="新密码">
                    <el-tooltip placement="right" popper-class="mypopper">
                        <div slot="content">密码规则提示：<br/>密码首字母必须大写
                            <br/>大小写字母、数字、特殊字符四选三
                            <br/>长度：8-16位
                        </div>
                        <el-input :type="showPWFlag?'text':'password'" v-model="passwdForm.newPasswd">
                            <i slot="suffix" :class="showPWFlag?'iconfont icon-yanjing':'iconfont icon-yanjing_bi'"
                               @click="showPWFlag=!showPWFlag"/>
                        </el-input>
                    </el-tooltip>

                </el-form-item>

                <el-form-item prop="confirmPasswd" label="再次确认">
                    <el-input type="password" v-model="passwdForm.confirmPasswd"></el-input>
                </el-form-item>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="changePasswd">确 定</el-button>
            </div>
        </el-dialog>
        <!--修改密码dialog end-->
    </div>

</template>

<script>


    export default {
        name: "User",
        inject: ["mainReload"],
        data() {
            let validatePasswd = (rule, value, callback) => {
                if (this.passwdForm.newPasswd !== value) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                authenticate(name) {
                    return this.$authenticate(this.$route.path, name)
                },
                userDatas: [],
                userQueryForm: {
                    status: '', name: '', mobile: '', beginTime: ''
                    , endTime: '', dateTimePickerValue: [], deptIds: []
                },
                dialogName: '',
                addUserVisible: false,
                userForm: {},
                userRules: {
                    name: [
                        {required: true, message: '请输入用户姓名', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入用户密码', trigger: 'blur'},
                        {
                            pattern: /^[A-Z]((?=.*\d)(?=.*[_!@#$%^&*`~()-+=])|(?=.*\d)(?=.*[a-z])|(?=.*[a-z])(?=.*[_!@#$%^&*`~()-+=]))[a-zA-Z0-9_!@#$%^&*`~()-+=]{7,17}$/,
                            message: "请根据密码提示规则输入密码",
                            trigger: "blur"
                        }
                    ],
                    mobile: [
                        //{required: false, message: '请输入用户手机号', trigger: 'blur'},
                        {pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/, message: "请输入合法手机号/电话号", trigger: "blur"}
                    ],
                    deptId: [
                        {required: true, message: '请选择归属部门', trigger: 'blur'}
                    ],
                    roleIds: [
                        {required: true, message: '请选择绑定角色', trigger: 'blur'}
                    ],
                    jobId: [
                        {required: true, message: '请选择用户岗位', trigger: 'blur'}
                    ],
                    sex: [
                        {required: true, message: '请选择用户性别', trigger: 'blur'}
                    ],
                    email: [
                        {
                            pattern: /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/,
                            message: '请输入正确格式的邮箱',
                            trigger: 'blur'
                        }
                    ],


                },

                // 部门树
                deptTree: [],

                //分页参数
                total: 0,
                pageNum: 1,
                pageSize: 10,

                // 删选部门文本
                filterText: '',

                //修改密码部分
                passwdVisible: false,
                passwdForm: {newPasswd: '', confirmPasswd: ''},
                passwdRules: {
                    newPasswd: [
                        {required: true, message: '请输入新密码', trigger: 'blur'}
                    ],
                    confirmPasswd: [
                        {required: true, message: '请再次确认新密码', trigger: 'blur'},
                        {
                            pattern: /^[A-Z]((?=.*\d)(?=.*[_!@#$%^&*`~()-+=])|(?=.*\d)(?=.*[a-z])|(?=.*[a-z])(?=.*[_!@#$%^&*`~()-+=]))[a-zA-Z0-9_!@#$%^&*`~()-+=]{7,17}$/,
                            message: "密码首位字母，后包含大小写、数字、特殊字符四选三，且在8～16位之间",
                            trigger: "blur"
                        },
                        {validator: validatePasswd, trigger: 'blur'}
                    ]
                },
                //修改密码部分
                //点击密码的小眼睛，标识符
                showPWFlag: false,

            }
        }
        ,

        watch: {
            filterText(val) {
                this.$refs.tree.filter(val);
            }
        }
        ,

        created() {

            //获取部门信息放到vuex中
            this.$axiosApi.getDeptTree('', (data) => {
                this.deptTree = data
                this.$store.dispatch("putDeptTree", data)
            })

            //获取用户数据
            this.$axiosApi.getUsers('', (data, total) => {
                this.userDatas = data
                this.total = total
            })

            //获取岗位数据放入vuex
            this.$get('/job/getJobList').then(({data}) => {
                this.$store.dispatch("putJobDatas", data)
            });

            //获取角色数据放入vuex
            this.$get("/role/getRoleList").then(({data}) => {
                this.$store.dispatch("putRoleDatas", data)
            })
        }
        ,

        computed: {

            dialogDeptTree: function () {
                return this.$store.state.deptTree
            }
            ,
            jobDatas: function () {
                return this.$store.state.jobDatas
            }
            ,
            roleDatas: function () {
                return this.$store.state.roleDatas
            }
            ,
        }
        ,

        methods: {
            init() {
                this.userForm = {
                    name: "",
                    roleIds: [],
                    deptId: "",
                    sex: this.$dictMapDefault('sex'),
                    status: this.$dictMapDefault('status')
                }

                this.passwdForm = {};
                this.showPWFlag = false
            },

            closeDialog() {

                this.addUserVisible = false;
                this.passwdVisible = false;

                this.init()
                this.$nextTick(() => {
                    this.$refs['userAddForm'].clearValidate()
                })
            },

            //节点过滤
            filterNode(value, data) {
                if (!value) return true;
                return data.name.indexOf(value) !== -1;
            }
            ,

            //分页插件，修改当前页号时触发
            handleCurrentChange(pageNum) {
                this.userQueryForm.pageNum = pageNum
                this.userQueryForm.pageSize = this.pageSize
                this.$axiosApi.getUsers(this.userQueryForm, (data, total) => {
                    this.userDatas = data
                    this.total = total
                    this.pageNum = pageNum
                })
            },

            //分页插件，条数修改时触发
            handleSizeChange(pageSize) {
                this.pageNum = 1;
                this.userQueryForm.pageNum = 1
                this.userQueryForm.pageSize = pageSize
                this.$axiosApi.getUsers(this.userQueryForm, (data, total) => {
                    this.userDatas = data
                    this.total = total
                    this.pageSize = pageSize
                })
            },

            formatTime(time) {
                if (time) {
                    this.userQueryForm.beginTime = time[0];
                    this.userQueryForm.endTime = time[1]
                }
            },

            //部门列表选择时，获取选择部门的所有子部门去查询
            deptChange(value) {
                this.userQueryForm.deptIds = []
                if (value.childDept) {
                    this.serverArray(value.childDept)
                }
                this.userQueryForm.deptIds.push(value.id)
                this.searchUser()
            },

            //迭代选择部门的所有子部门
            serverArray(arr) {
                for (let index = 0; index < arr.length; index++) {
                    this.userQueryForm.deptIds.push(arr[index].id)
                    if (arr[index].childDept) {
                        this.serverArray(arr[index].childDept)
                    }
                }
            },

            //控制状态的开关按钮触发
            statusChange(user) {
                this.$put("/user/editUser", user).then(() => {
                    if (user.status === "1") {
                        this.$message({
                            message: "已开启",
                            type: 'success'
                        });
                    } else {
                        this.$message("已禁用")
                    }
                })
            },

            //查询模块，搜索按钮
            searchUser() {
                //点击搜索后，要重置pageNum和pageSize，以免被之前的分页参数影响
                this.pageNum = 1
                this.pageSize = 10
                this.userQueryForm.pageNum = 1;
                this.userQueryForm.pageSize = 10;
                this.$axiosApi.getUsers(this.userQueryForm, (data, total) => {
                    this.userDatas = data
                    this.total = total
                })
            },

            //删除用户
            delUser(user, index) {
                this.$confirm(`确定永久删除 '${user.name}' 用户吗？`, '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    this.$del("/user/delUser", {
                        id: user.id
                    }).then(() => {
                        this.$message("删除成功");
                        this.mainReload();
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: "已取消删除"
                    });
                });

            },

            addUser() {
                this.addUserVisible = true;
                this.dialogName = '添加用户';
                this.init();
            },

            //点击编辑按钮触发
            editUser(userForm) {
                this.dialogName = '编辑用户'
                this.addUserVisible = true;
                this.userForm = JSON.parse(JSON.stringify(userForm));
            },

            // 添加/编辑框 点击确认的时候
            oprUser() {
                //form表单规则校验
                this.$refs['userAddForm'].validate(async (valid) => {
                    if (!valid) {
                        return false
                    }

                    // 该方法用来处理新增还是处理编辑，关键在于查看this.roleForm对象是否具有id，有就是编辑，无这是新增
                    if (!this.userForm.id) {
                        await this.$post("/user/addUser", this.userForm)
                    } else {
                        try {
                            await this.$put("/user/editUser", this.userForm)
                        } catch (e) {
                            this.addUserVisible = false;
                            return
                        }
                    }

                    // 关闭编辑框
                    this.addUserVisible = false

                    // 提示框
                    this.$message({
                        message: "操作成功",
                        type: "success",
                    })

                    // 因为编辑的时候可能已经添加了id，记得要清除id
                    this.userForm.id = '';
                    this.userForm.roleIds = [];
                    this.userForm.deptId = ''
                    this.userForm.jobId = ''

                    //密码框重新设为password类型
                    this.type = false
                    //重新装载数据 todo key值写成枚举
                    this.mainReload();
                });
            },

            changePasswd() {
                this.$refs['passwdForm'].validate(async (valid) => {
                    if (!valid) {
                        return false
                    }
                    this.userForm.password = this.passwdForm.newPasswd;
                    this.$put("/user/editUser", this.userForm).then(() => {
                        this.$message({
                            message: "操作成功",
                            type: "success",
                        })
                        this.userForm = {status: 1}
                        this.passwdForm = {}
                        this.passwdVisible = false
                    });
                })
            }
        }
    }
</script>

<style>


</style>

<style scoped>
    .left {
        margin-right: 40px;
        width: 200px;
        border: 1px solid #ebeef5;
        border-radius: 0;
        padding: 20px;
    }

    /*.el-dialog .el-form-item {*/
    /*    margin-bottom: 45px;*/
    /*}*/

</style>